import queue
import threading

class MessageQueue:
    """线程安全的消息队列，用于进程间通信(IPC)"""
    
    def __init__(self):
        # 创建两个队列：一个用于发送到GUI，一个用于从GUI接收
        self.to_gui_queue = queue.Queue()
        self.from_gui_queue = queue.Queue()
        self.running = False
        self.gui_listener = None
        
    def start_gui_listener(self, gui_callback):
        """启动GUI线程的消息监听器"""
        self.running = True
        
        def listen():
            while self.running:
                try:
                    # 等待消息，超时100ms以便检查running状态
                    message = self.to_gui_queue.get(timeout=0.1)
                    # 处理消息并获取结果
                    result = gui_callback(message)
                    # 将结果放回队列
                    #self.from_gui_queue.put(result)
                except queue.Empty:
                    continue
                except Exception as e:
                    print(f"消息处理错误: {e}")
                    self.from_gui_queue.put(None)
        
        self.gui_listener = threading.Thread(target=listen)
        self.gui_listener.daemon = True
        self.gui_listener.start()
        
    def stop_gui_listener(self):
        """停止GUI监听器"""
        self.running = False
        if self.gui_listener:
            self.gui_listener.join()
            
    def send_to_gui(self, message):
        """向GUI线程发送消息"""
        self.to_gui_queue.put(message)
        
    def send_to_api(self, message):
        self.from_gui_queue.put(message)

    def receive_from_gui(self, timeout=None):
        """从GUI线程接收结果"""
        try:
            return self.from_gui_queue.get(timeout=timeout)
        except queue.Empty:
            return None
    
    def clear_queue_from_gui(self):
        while not self.from_gui_queue.empty():
            try:
                self.from_gui_queue.get_nowait()
            except queue.Empty:
                break
            self.from_gui_queue.task_done()
